<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Library\Common;
use App\Model\FlyCoupon;
use App\Model\FlyCouponGood;
use App\Model\FlyCouponUser;
use Exception;
use Hyperf\DbConnection\Db;
use RuntimeException;

class FlyCouponService extends BaseService
{

    const USE_TYPE_SHOP = 1;
    const USE_TYPE_PRODUCT = 2;

    /**
     * @param array $params
     * @param int $shop_id
     * @param int $type 1全部  2用户可用
     * @return array|object
     */
    public function index(array  $params,int  $shop_id,$type=1)
    {
        $where['shop_id'] = $shop_id;
        if (!empty($params['coupon_name'])) {
            $where[] = ['coupon_name','like','%'.$params['coupon_name'].'%'];
        }
        $coupon_ids = [];
        if(isset($params['product_id'])&&$params['product_id']!=''){
           $coupon_ids  =  FlyCouponGood::query()->where('product_id',$params['product_id'])->pluck('coupon_id')->toArray();
        }
        if($type==2){
            $where['status'] = 1;
        }
        if(isset($params['status'])&&$params['status']!=''){
            $where['status'] = $params['status'];
        }
        if($type==2){
            $time = Common::date_time(2);
            $where[] = ['use_begin_time','<',$time];
            $where[] = ['use_end_time','>',$time];
        }
        if(isset($params['product_id'])&&$params['product_id']!=''){
            $model = New FlyCoupon();
            return  $model
                ->where($where)
                ->when(isset($params['product_id'])&&$params['product_id']!='',function ($query) use ($coupon_ids,$where) {
                    $query->where($where)->orwhere('id','in',$coupon_ids);
                })
                ->with('create_info')
                ->with('update_info')
                ->with('link_product')
                ->orderBy('id','DESC');
        }else{
            return FlyCoupon::query()
                ->where($where)
                ->with('create_info')
                ->with('update_info')
                ->with('link_product')
                ->orderBy('id','DESC');
        }
    }

    /**
     * Notes:
     * @param int $user_id
     * @param int $type
     * @param int $is_used
     * @return \Hyperf\Database\Model\Builder
     * Date: 2022/8/19
     * Time:17:23
     * Auth: zdl
     */
//    优惠券列表
    public function user_coupon(int $user_id,$is_used=0,$type=1)
    {
//        未过期
        $fields = ['fly_coupon_user.*','fc.id as coupon_id'];
        $time = Common::date_time(2);
        if($type==1){
            return  FlyCouponUser::query()
                ->leftJoin('fly_coupon as fc','fc.id','=','fly_coupon_user.coupon_id')
                ->where('user_id',$user_id)
                ->where('is_used',$is_used)
                ->where('fc.use_begin_time','<',$time)
                ->where('fc.use_end_time','>',$time)
                ->orderBy('fly_coupon_user.id','DESC')
                ->with('coupon_info')->select($fields);
        }else{
//            ，已过期
            return  FlyCouponUser::query()
                ->leftJoin('fly_coupon as fc','fc.id','=','fly_coupon_user.coupon_id')
                ->where('user_id',$user_id)
                ->where('is_used',$is_used)
                ->where('fc.use_end_time','<',$time)
                ->orderBy('fly_coupon_user.id','DESC')
                ->with('coupon_info')->select($fields);
        }

    }
    /**
     * @param array $couponData
     * @param int $shop_id
     * @return int
     */
//    优惠券添加
    public function coupon_insert(array $couponData, int $shop_id)
    {
        $couponData['last_num'] = $couponData['total_num'];
        $couponData['shop_id'] = $shop_id;
        $product_list = [];
        if(isset($couponData['product_list'])){
            $product_list = $couponData['product_list'];unset($couponData['product_list']);
        }
        if($product_list!=[]){
            $coupon_id =   $this->insertAndGetId($couponData);
            $this->insert_goods($product_list,$shop_id,$coupon_id);
            return $coupon_id;
        }else{
            return  $this->insertAndGetId(Common::filter_null($couponData));
        }
    }

    //    优惠券添加
    public function insert_goods(array $product_list, int $shop_id,int $coupon_id)
    {
        $insert_arr = [];
       foreach ($product_list as $key=>$value){
           $insert_arr[] = [
               'shop_id'=>$shop_id,
               'coupon_id'=>$coupon_id,
               'product_id'=>$value,
           ];
       }
       FlyCouponGood::query()->insert($insert_arr);
    }


    /**
     * @param array $upData
     * @return bool
     */
    //    优惠修改
    public function coupon_update(array $upData)
    {
        $product_list = [];
        if(isset($upData['product_list'])){
            $product_list = $upData['product_list'];unset($upData['product_list']);
        }
        if($product_list!=[]){
            $this->insert_goods($product_list,$upData['shop_id'],$upData['id']);
        }

        return  $this->update_insert(['id'=>$upData['id']],Common::filter_null($upData));
    }

    /**
     * 获取优惠券详情
     * @param int $coupon_id
     * @return array|null
     */
    public function get_coupon_info(int $coupon_id): array
    {
        $instance = $this->getModelInstance()->find($coupon_id);
       return empty($instance) ? [] : $instance->toArray();
    }

    /**
     * Notes:领取优惠券
     * @param int $coupon_id
     * @param int $user_id
     * @return bool|int|array
     * Date: 2022/8/19
     * Time:14:16
     * Auth: zdl
     */
    public function receive_coupon(int $coupon_id, int $user_id)
    {
        $coupon_info =  $this->get_coupon_info($coupon_id);
        $user_coupon_total = FlyCouponUser::query()
            ->where('user_id',$user_id)
            ->where('coupon_id',$coupon_id)
            ->count('id');
        if($coupon_info['last_num']==0){
            throw new RuntimeException("该优惠券售罄了！", ErrorCode::SERVER_ERROR);
        }
        if($coupon_info['single_num']<=$user_coupon_total){
            throw new RuntimeException("该优惠券用户领取数量上限：".$coupon_info['single_num'], ErrorCode::SERVER_ERROR);
        }
        Db::beginTransaction();
        try {
//            发送数量+1
            $FlyCoupon = New FlyCoupon();
            $FlyCoupon->where('id',$coupon_id)->increment('send_num');
            if($coupon_info['total_num']!=-1){
//                非无限制的，有限制数量的，计算剩余数量 -1
                $FlyCoupon->where('id',$coupon_id)->decrement('last_num');
            }
//            发送给用户并记录
            $id = FlyCouponUser::query()->insertGetId([
                'shop_id'=>$coupon_info['shop_id'],
                'coupon_id'=>$coupon_info['id'],
                'created_at'=>Common::date_time(2),
                'user_id'=>$user_id,
                'type'=>2,
                'use_product_type'=>$coupon_info['use_product_type'],
            ]);
            Db::commit();
            return $id;
        }catch (Exception $e){
            Db::rollBack();
            var_dump($e->getMessage());
            return false;
        }
    }

    //    用户商品可用优惠券
    public function products_usable_coupon(array $product_ids,$use_product_type, $user_id,$shop_id)
    {
    //    商品可用的数组
        $where = [];
        $time = Common::date_time(2);
        $where[] = ['use_begin_time','<',$time];
        $where[] = ['use_end_time','>',$time];
        $coupon_ids_a = FlyCouponGood::query()
            ->leftJoin('fly_coupon as fc','fc.id','=','fly_coupon_goods.coupon_id')
            ->whereIn('fly_coupon_goods.product_id',$product_ids)
            ->where('fc.shop_id',$shop_id)
            ->where($where)
            ->pluck('coupon_id')
            ->toArray();
        $coupon_ids_b = FlyCoupon::query()
            ->where('shop_id',$shop_id)
            ->where($where)
            ->pluck('id')
            ->toArray();
        $coupon_ids =array_unique(array_merge($coupon_ids_a,$coupon_ids_b));
        return  FlyCouponUser::query()
            ->whereIn('coupon_id',$coupon_ids)
            ->where('user_id',$user_id)
            ->where('use_product_type',$use_product_type)
            ->where('is_used',0)
            ->with('coupon_info');
    }
}